import { Uploader, ConfigProvider } from '@nutui/nutui-react-taro';
import Taro from '@tarojs/taro';

import { StorageKey } from '@/constants/storage';
import type { UploaderProps as NutUploaderProps } from '@nutui/nutui-react-taro/dist/types/packages/uploader/uploader.taro';
import type { FileItem } from '@nutui/nutui-react-taro/dist/types/packages/uploader/file-item';

import type { FC } from 'react';

interface UploadFileResponse {
  files: FileItem[];
  option: Record<string, any>;
  responseText: {
    data: string;
  };
}

interface UploaderProps
  extends Omit<Partial<NutUploaderProps>, 'onChange' | 'value' | 'url'> {
  onChange?: (value: string[]) => void;
  value?: string[];
}

const CustomUploader: FC<UploaderProps> = ({
  onChange,
  value = [],
  maxCount = 4,
  ...rest
}) => {
  console.log('value', value);

  // 处理文件变化
  const handleChange = (files: FileItem[]) => {
    console.log('files', files);

    onChange?.(handleFormatData.out(files));
  };

  // 处理上传成功
  const handleSuccess = (param: UploadFileResponse) => {
    console.log('Upload success:', param);

    // 解析响应数据，获取上传后的文件URL
    let responseData;
    try {
      // responseText 是一个对象，data 字段是字符串需要再次解析
      const responseTextData = param.responseText?.data || param.responseText;
      responseData =
        typeof responseTextData === 'string'
          ? JSON.parse(responseTextData)
          : responseTextData;
    } catch (e) {
      console.error('Failed to parse response:', e);
      return;
    }

    // 根据实际的响应格式获取文件URL
    // 根据你的接口返回格式：{"result":1,"code":"1000","msg":"success","data":"...","success":true}
    const uploadedUrl = responseData?.data || responseData?.url;

    console.log('uploadedUrl', uploadedUrl);

    if (uploadedUrl) {
      // 触发回调
      onChange?.([...value, uploadedUrl]);
    }
  };

  // 处理数据
  const handleFormatData = {
    in: (values: string[]) => {
      // 转化成File文件类型
      return values.map((url) => ({
        uid: `file-${url}`,
        url,
        status: 'success' as const,
        message: '',
        type: 'image',
      }));
    },
    out: (files: FileItem[]) => {
      // 转化成字符串数组
      return files
        .filter((file) => file.status === 'success' && file.url)
        .map((file) => file.url!);
    },
  };

  return (
    <ConfigProvider
      theme={{
        '--nutui-uploader-image-width': '76px',
        '--nutui-uploader-image-height': '76px',
      }}
    >
      <Uploader
        {...rest}
        maxCount={maxCount}
        autoUpload
        value={handleFormatData.in(value)}
        onChange={handleChange}
        url="https://labor-test.jiuworker.com/airy/api/url/address"
        headers={{
          labToken: Taro.getStorageSync(StorageKey.TOKEN),
        }}
        onSuccess={handleSuccess as any}
      />
    </ConfigProvider>
  );
};

// 导出增强版组件
export { default as EnhancedUploader } from './EnhancedUploader';

export default CustomUploader;
